﻿using UnityEngine;
using SimpleJSON;

public class NativeManager : ModuleBase<NativeManager>
{
    public delegate void CallbackHandler(string args);
    CallbackHandler m_callback;

    NativeAgent m_agent;

    public NativeManager()
    {
        GameObject go = new GameObject("NativeAgent");
        Object.DontDestroyOnLoad(go);

        m_agent = go.AddComponent<NativeAgent>();
    }

    // 调用原生代码
    public string CallNative(string args)
    {
        if (m_agent == null)
        {
            return "{\"error\":0}";
        }
        return m_agent.CallNative(args);
    }

    public string CallNativeMethodName(string name)
    {
        JSONClass json = new JSONClass();
        json.Add("method_name", new JSONData(name));

        return CallNative(json.ToString(""));
    }

    public void SetNativeCallback(CallbackHandler func)
    {
        m_callback = func;
    }

    // 原生代码回调
    internal void NativeCallback(string args)
    {
        if (m_callback != null)
        {
            m_callback(args);
        }
    }
}